package com.zookeeper;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

public class ZooKeeperDistributed {

    public static void main(String[] args) throws Exception{
        new ZooKeeperDistributed();
    }

        private final int SESSION_TIMEOUT=2000;
        private int i=1;
        ZooKeeper zk=null;

        private final String ROOT_LOCK ="/lock";

        private String REG_PATH="";

        Watcher watcher = new Watcher() {
            public void process(WatchedEvent watchedEvent){
                if(watchedEvent.getType()==Event.EventType.NodeChildrenChanged){
                    System.out.println(REG_PATH+"Enter  watcher");

                }

            }
        };

        //connected zk，register monitor
        public ZooKeeperDistributed() throws Exception{
            zk=new ZooKeeper("192.168.200.200, 192.168.200.201, 192.168.200.202", SESSION_TIMEOUT, watcher);
            Stat stat = zk.exists(ROOT_LOCK , false);
            // if there is no father node ,the father node is created
            // 如果没有父节点则直接创建父节点

            if(stat==null){
                zk.create(ROOT_LOCK,null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
            //register
            register();
        }

        //register one node  注册一个节点
        public void register() throws Exception{
            REG_PATH=zk.create(ROOT_LOCK + "/", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
            System.out.println(REG_PATH+"the node was registered successfull ");
            business();
        }
        // Release lock  释放锁，直接删除节点
        public void releaseLock()throws Exception{
            zk.delete(REG_PATH,-1);
            System.out.println(REG_PATH+"the lock was deleted successfull");
        }

        public void business()throws Exception{
            i++;
            System.err.println(REG_PATH+" Business Processing...");
            Thread.sleep((long) Math.random()*50000+500);
            System.err.println(REG_PATH+" Business process completed...");
            releaseLock();
            while(i<=3){
                register();
            }
            System.out.println("3 times");
            System.exit(-1);
        }


}
